import $config from '@/api/http.baseUrl.js';

/**
 * @description 加密手机号
 * @param {String Number} mobile 手机号
 */
export function cellPhone(mobile) {
	mobile = "" + mobile;
	let resultPhone = mobile.replace(/^(\d{3})\d{4}(\d+)/, '$1****$2');
	return resultPhone
}


/**
 * @description 拨打电话
 * @param {String,Number} tel 手机号
 */
export function makePhoneCall(tel) {
	uni.makePhoneCall({
		phoneNumber: tel
	})
}



/**
 * @description 退出登录
 */
export function quitLogin() {
	// uni.clearStorage()

	uni.removeStorage({
		key: 'token',
	})
	uni.reLaunch({
		url: '/pages/login/index'
	})
}





/**
 * @description 复制
 * @param 复制内容
 */
export function copy(value) {
	//uni.setClipboardData方法将内容复制到粘贴板
	uni.setClipboardData({
		data: value, //要被复制的内容
		success: () => { //复制成功的回调函数
			uni.showToast({ //提示
				title: '复制成功'
			})
		}
	});
}



/**
 * @description 保存图片到本机
 * @param 图片链接
 */
export function shareImg(dataurl) {
	uni.chooseImage({
		count: 1,
		sourceType: ['camera'],
		success: function (res) {
			uni.saveImageToPhotosAlbum({
				filePath: res.tempFilePaths[0],
				success: function () {
					console.log('save success');
				}
			});
		}
	});
}



/**
 * @description 微信登录
 */
export function weChatLogin() {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			onlyAuthorize: true, // 微信登录仅请求授权认证
			success: function (event) {
				resolve(event)
			},
			// fail: function(err) {
			// 	reject(err)
			// }
		});
	})
}



/**
 * @description 上传图片
 */
export function uploadImg(url) {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], //从相册、相机选择
			success: res => {
				console.log(res.tempFilePaths[0], this.$baseUrl);
				uni.uploadFile({
					url: $config.baseUrl + '/index.php/shop/upload/postUploadOneImg',
					filePath: res.tempFilePaths[0],
					name: 'img',
					header: {
						'Content-Type': 'multipart/form-data'
					},
					success: result => {
						console.log('resolve', result);
						if (result.statusCode == 200) {
							return result
						}
					}
				});
			}
		})
	});
}


/**
 * @description 上传文件
 */
export function uploadFiles(file) {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				uni.uploadFile({
					url: `${$config.baseUrl}/system/basic/postUploadOne`, //仅为示例，非真实的接口地址
					filePath: tempFilePaths[0],
					name: 'img',
					formData: {
						'type': 'file'
					},
					success: (uploadFileRes) => {
						uni.showToast({
							title: '上传成功',
							duration: 1000
						});
						let file = JSON.parse(uploadFileRes.data);
						resolve(file)
					}
				});

			}
		});
	})
}



/**
 * @description 获取缓存
 */
export function getStorageSize() {
	let fileSizeString = ''
	plus.cache.calculate(function (size) {
		let sizeCache = parseInt(size);
		if (sizeCache == 0) {
			fileSizeString = "0B";
		} else if (sizeCache < 1024) {
			fileSizeString = sizeCache + "B";
		} else if (sizeCache < 1048576) {
			fileSizeString = (sizeCache / 1024).toFixed(2) + "K";
		} else if (sizeCache < 1073741824) {
			fileSizeString = (sizeCache / 1048576).toFixed(2) + "M";
		} else {
			fileSizeString = (sizeCache / 1073741824).toFixed(2) + "G";
		}
	});
	return fileSizeString
}



/**
 * @description 清除缓存
 */
export function clearStorage() {
	let that = this;
	let os = plus.os.name;
	if (os == 'Android') {
		let main = plus.android.runtimeMainActivity();
		let sdRoot = main.getCacheDir();
		let files = plus.android.invoke(sdRoot, "listFiles");
		let len = files.length;
		for (let i = 0; i < len; i++) {
			let filePath = '' + files[i]; // 没有找到合适的方法获取路径，这样写可以转成文件路径
			plus.io.resolveLocalFileSystemURL(filePath, function (entry) {
				if (entry.isDirectory) {
					entry.removeRecursively(function (entry) { //递归删除其下的所有文件及子目录
						uni.showToast({
							title: '缓存清理完成',
							duration: 2000
						});
						that.getStorageSize(); // 重新计算缓存
					}, function (e) {
						console.log(e.message)
					});
				} else {
					entry.remove();
				}
			}, function (e) {
				console.log('文件路径读取失败')
			});
		}
	} else { // ios
		plus.cache.clear(function () {
			uni.showToast({
				title: '缓存清理完成',
				duration: 2000
			});
			that.getStorageSize();
		});
	}
}

export const pay = (data, type) => {
	return new Promise((resolve, reject) => {
		if (type == 'alipay') {
			uni.requestPayment({
				provider: type,
				orderInfo: data,
				// timeStamp: res.data.
				success: res => {
					resolve(res)
				},
				fail(err) {
					reject(false)
				}
			})
		} else {
			// console.log(type, data)
			uni.requestPayment({
				provider: type,
				orderInfo: data,
				success: res => {
					resolve(res)
				},
				fail(err) {
					console.log(err)
					reject(false)
				}
			})
		}
	})
}


// App微信支付宝支付
export async function wxPay(params, provider) {
	console.log('params: ', params);
	return new Promise(async (resolve, reject) => {
		// #ifdef APP-PLUS
		uni.requestPayment({
			provider: provider,
			orderInfo: provider == 'wxpay' ? JSON.parse(params) : params,
			success: (suc) => {
				resolve(suc); //返回写函数里面你要执行的内容
			},
			fail: (f) => {
				console.log(f)
				reject(f)
			}
		});
		// #endif

		// #ifdef MP-WEIXIN
		uni.requestPayment({
			provider: provider,
			...params,
			success: (suc) => {
				resolve(suc); //返回写函数里面你要执行的内容
			},
			fail: (f) => {
				console.log(f)
				reject(f)
			}
		});
		// #endif
	})
}

/**
 * 随机字符串
 */
export const generateRandomString = (length) => {
	const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
	let result = ''
	for (let i = 0; i < length; i++) {
	    const randomIndex = Math.floor(Math.random() * characters.length)
	    result += characters[randomIndex]
	}
	return result
}

/**
 * 获取当前秒数
 */
export const getNowSecond = () => {
	let now = Date.now()
	let second = parseInt(now / 1000)
	
	return second.toString()
}
